home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Amiga Format CD 23
/
Amiga Format AFCD23 (Feb 1998, Issue 107).iso
/
-in_the_mag-
/
emulation
/
consoles
/
amigavgb
/
demos
/
rpn.c
< prev
next >
Wrap
C/C++ Source or Header
|
1997-12-12
|
1KB
|
103 lines
#include <stdlib.h>
#include <stdio.h>
#define MAXOP 40
#define NUMBER '0'
#define STACKSIZE 40
int sp;
int stack[STACKSIZE];
char s[MAXOP];
int pos;
int n;
void push(int i)
{
if(sp < STACKSIZE)
stack[sp++] = i;
else
puts("Stack full");
}
int pop()
{
if(sp > 0)
return stack[--sp];
else
puts("Stack empty");
return 0;
}
int top()
{
if(sp > 0)
return stack[sp-1];
else
puts("Stack empty");
return 0;
}
int read_op()
{
if(pos == -1) {
gets(s);
pos = 0;
}
while(s[pos] == ' ' || s[pos] == '\t')
pos++;
if(s[pos] == '\0') {
pos = -1;
return('\n');
}
if(!isdigit(s[pos]))
return(s[pos++]);
n = s[pos] - '0';
while(isdigit(s[++pos]))
n = 10 * n + s[pos] - '0';
return NUMBER;
}
void main()
{
int type;
int op2;
puts("RPN Calculator");
sp = 0;
pos = -1;
while((type = read_op(s)) != EOF) {
switch(type) {
case NUMBER:
push(n);
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if(op2 != 0)
push(pop() / op2);
else
puts("Divide by 0");
break;
case '\n':
printf("==> %d\n", top());
break;
}
}
}